<template>
  <el-dialog
    v-model="dialogVisible"
    title="商品"
    width="30%"
    style="min-width: 700px"
    draggable
  >
    <el-form label-position="top">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="商品货号">
            <el-input
              size="large"
              placeholder="商品货号"
              clearable
              v-model="requestParam.numberStr"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="条形码">
            <el-input
              size="large"
              placeholder="条形码（光标于此处时，可直接扫描条形码）"
              clearable
              v-model="requestParam.barCode"
              autocomplete="off"
            ></el-input>
            <el-button type="text" @click="createBarCode()"
              >生成条形码</el-button
            >
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="条形码图片">
            <img
              id="code128"
              v-show="requestParam.barCode != null"
              style="width: 100%; height: 100%"
            />
            <div
              v-show="
                requestParam.barCode == null || requestParam.barCode == ''
              "
            >
              暂无条形码内容
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="名称">
            <el-input
              size="large"
              :placeholder="'名称'"
              clearable
              v-model="requestParam.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="展示图">
            <uploadImage
              @change="fileChange"
              :fileIdOfImgArr="requestParam.fileIdOfImgArrStr"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="分类">
            <el-button
              v-if="goodsType.id == null"
              @click.prevent="toSelectType()"
              >选择商品分类</el-button
            >
            <el-button v-else @click.prevent="toSelectType()">{{
              goodsJs.getGoodsTypeFullName(goodsType)
            }}</el-button>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="单价（单位：￥）">
            <el-input-number
              size="large"
              :placeholder="'单价'"
              clearable
              v-model="requestParam.price"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="库存">
            <el-input-number
              size="large"
              :placeholder="'库存'"
              clearable
              v-model="requestParam.stock"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="库存预警下限">
            <el-input-number
              size="large"
              :placeholder="'库存预警下限'"
              clearable
              v-model="requestParam.stockWarningLower"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="库存预警上限">
            <el-input-number
              size="large"
              :placeholder="'库存预警上限'"
              clearable
              v-model="requestParam.stockWarningUpper"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="零售价（单位：￥）">
            <el-input-number
              size="large"
              :placeholder="'零售价'"
              clearable
              v-model="requestParam.retailPrice"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="批发价（单位：￥）">
            <el-input-number
              size="large"
              :placeholder="'批发价'"
              clearable
              v-model="requestParam.wholesalePrice"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="采购价（单位：￥）">
            <el-input-number
              size="large"
              :placeholder="'采购价'"
              clearable
              v-model="requestParam.purchasePrice"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="起订量">
            <el-input-number
              size="large"
              :placeholder="'起订量'"
              clearable
              v-model="requestParam.minOrder"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="优先级">
            <el-input-number
              size="large"
              :placeholder="'优先级'"
              clearable
              v-model="requestParam.priority"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template v-slot:footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit()"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
  <GoodsTypeSelect
    ref="goodsTypeSelect"
    @select="goodsSelectSelect"
  ></GoodsTypeSelect>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineExpose, watch } from "vue";
let dialogVisible = ref(false);
import $kt from "@/vueKantboot";
import { ElLoading, ElMessage } from "element-plus";
import { de, fa } from "element-plus/es/locale";
import uploadImage from "@/components/uploadImage/uploadImage.vue";
import GoodsTypeSelect from "@/components/goodsTypeSelect/goodsTypeSelect.vue";
import goodsJs from "@/commonJs/goods/index.js";
import JsBarcode from "jsbarcode";

// emits
let emits = defineEmits(["submit"]);

let requestParamStart = {
  // 条形码
  barCode: null,
  // 名称
  name: null,
  // 展示图
  fileIdOfImgArrStr: "[]",
  // 单价
  price: null,
  // 库存
  stock: null,
  // 库存预警下限
  stockWarningLower: null,
  // 库存预警上限
  stockWarningUpper: null,
  // 零售价
  retailPrice: null,
  // 批发价
  wholesalePrice: null,
  // 采购价
  purchasePrice: null,
  // 起订量
  minOrder: null,
  // 优先级
  priority: null,
  // 商品分类id
  typeId: null,
  // 商品货号
  numberStr: null,
};

let requestParam = ref(JSON.parse(JSON.stringify(requestParamStart)));

// 是否文件正在上传
let isFileUploading = ref(false);

/**
 * 打开弹窗
 */
let open = (param: any) => {
  if (param) {
    requestParam.value = JSON.parse(JSON.stringify(param));
  }

  if (requestParam.value.barCode != null && requestParam.value.barCode != "") {
    createBarCode();
  }

  dialogVisible.value = true;
};

let fileChange = (json: any) => {
  requestParam.value.fileIdOfImgArrStr = json.str;
};

let createBarCodeImg = () => {
  if (requestParam.value.barCode == null) {
    return false;
  }
  setTimeout(() => {
    JsBarcode("#code128", requestParam.value.barCode, {
      format: "CODE128",
      lineColor: "#000",
      width: 2,
      height: 100,
      displayValue: true,
    });
  }, 500);
};

let createBarCode = () => {
  if (requestParam.value.numberStr == null) {
    // 生成一个0-9999随机数
    requestParam.value.barCode = Math.floor(Math.random() * 10000).toString();
    // 如果少于13位，前面补0
    while (requestParam.value.barCode.length < 13) {
      requestParam.value.barCode = "0" + requestParam.value.barCode;
    }
    return false;
  }

  if (requestParam.value.numberStr == requestParam.value.barCode) {
    // 如果相等,就加一个0-9999随机数
    requestParam.value.barCode =
      requestParam.value.barCode + Math.floor(Math.random() * 10000).toString();
    // 如果少于13位，前面补0
    while (requestParam.value.barCode.length < 13) {
      requestParam.value.barCode = "0" + requestParam.value.barCode;
    }
    return false;
  }

  requestParam.value.barCode = requestParam.value.numberStr;
};

// 监听条形码变化
watch(
  () => requestParam.value.barCode,
  (newValue, oldValue) => {
    createBarCodeImg();
  }
);

let submit = () => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });

  $kt.request
    .request({
      url: "/business-goods-web/admin/goods/save",
      method: "post",
      data: requestParam.value,
    })
    .then((res) => {
      if (res.data.success) {
        ElMessage({
          message: "保存成功",
          type: "success",
        });
        dialogVisible.value = false;

        loading.close();
        // 提交
        emits("submit");
        dialogVisible.value = false;
        requestParam.value = JSON.parse(JSON.stringify(requestParamStart));
        return false;
      }
      ElMessage({
        message: res.data.errMsg,
        type: "error",
      });
    });
};

let goodsTypeSelect = ref();

let toSelectType = (param: any) => {
  goodsTypeSelect.value.open();
};

let goodsType = ref({
  id: null,
  name: null,
});

let goodsSelectSelect = (res: any) => {
  requestParam.value.typeId = res.id;
  goodsType.value = res;
};

// 暴露给父组件的方法
defineExpose({
  open,
});
</script>

<style lang="scss" scoped>
.img-uploaded {
  cursor: pointer;
}

.img-uploaded:hover {
  opacity: 0.8;
}
</style>
